package com.ruoyi.framework.security.provider;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

public class CodeAuthenticationProvider implements AuthenticationProvider {
    private UserDetailsService userDetailsService;

    public CodeAuthenticationProvider() {
    }


    public CodeAuthenticationProvider(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        CodeAuthenticationToken authenticationToken = (CodeAuthenticationToken) authentication;
        String employeeCode = (String) authenticationToken.getPrincipal();
        UserDetails userDetails = userDetailsService.loadUserByUsername(employeeCode);
        // 此时鉴权成功后，应当重新 new 一个拥有鉴权的 authenticationResult 返回
        CodeAuthenticationToken authenticationResult = new CodeAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }



    @Override
    public boolean supports(Class<?> authentication) {
        return CodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
